#!/usr/bin/env python3
"""
DataPlexus 数据源管理集成验证脚本
验证路由配置、权限集成、菜单显示等功能
"""

import sys
import os
import asyncio
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from app.core.database import get_async_session
from app.models.auth import Route, Permission, RoutePermission, Role, RolePermission, User
from app.core.logger import logger


class DataSourceIntegrationVerifier:
    """数据源管理集成验证器"""
    
    def __init__(self):
        self.verification_results = {
            'route_config': False,
            'route_permissions': False,
            'menu_display': False,
            'permission_assignment': False,
            'user_access': False
        }
    
    async def verify_route_configuration(self, db: AsyncSession) -> dict:
        """验证路由配置"""
        logger.info("验证数据源管理路由配置...")
        
        try:
            # 检查数据源管理路由是否存在
            stmt = select(Route).where(Route.path == '/datasources')
            result = await db.execute(stmt)
            datasource_route = result.scalar_one_or_none()
            
            if not datasource_route:
                return {
                    'success': False,
                    'message': '数据源管理路由不存在',
                    'details': '需要运行路由初始化脚本'
                }
            
            # 验证路由属性
            route_checks = {
                'path': datasource_route.path == '/datasources',
                'name': datasource_route.name == 'datasources',
                'display_name': datasource_route.display_name == '数据源管理',
                'icon': datasource_route.icon == 'DatabaseOutlined',
                'component': datasource_route.component == 'DataSourceManagement',
                'is_menu': datasource_route.is_menu == True,
                'is_active': datasource_route.is_active == True
            }
            
            failed_checks = [key for key, value in route_checks.items() if not value]
            
            if failed_checks:
                return {
                    'success': False,
                    'message': f'路由配置不正确: {", ".join(failed_checks)}',
                    'details': {
                        'route_id': datasource_route.id,
                        'current_config': {
                            'path': datasource_route.path,
                            'name': datasource_route.name,
                            'display_name': datasource_route.display_name,
                            'icon': datasource_route.icon,
                            'component': datasource_route.component,
                            'is_menu': datasource_route.is_menu,
                            'is_active': datasource_route.is_active
                        },
                        'failed_checks': failed_checks
                    }
                }
            
            self.verification_results['route_config'] = True
            return {
                'success': True,
                'message': '路由配置正确',
                'details': {
                    'route_id': datasource_route.id,
                    'path': datasource_route.path,
                    'display_name': datasource_route.display_name,
                    'sort_order': datasource_route.sort_order
                }
            }
            
        except Exception as e:
            logger.error(f"验证路由配置失败: {str(e)}")
            return {
                'success': False,
                'message': f'验证路由配置时发生错误: {str(e)}',
                'details': None
            }
    
    async def verify_route_permissions(self, db: AsyncSession) -> dict:
        """验证路由权限关联"""
        logger.info("验证数据源管理路由权限关联...")
        
        try:
            # 获取数据源管理路由
            route_stmt = select(Route).where(Route.path == '/datasources')
            route_result = await db.execute(route_stmt)
            datasource_route = route_result.scalar_one_or_none()
            
            if not datasource_route:
                return {
                    'success': False,
                    'message': '数据源管理路由不存在',
                    'details': None
                }
            
            # 检查路由权限关联
            rp_stmt = select(RoutePermission).join(Permission).where(
                RoutePermission.route_id == datasource_route.id
            )
            rp_result = await db.execute(rp_stmt)
            route_permissions = rp_result.scalars().all()
            
            if not route_permissions:
                return {
                    'success': False,
                    'message': '数据源管理路由未关联任何权限',
                    'details': '需要运行权限关联脚本'
                }
            
            # 获取关联的权限详情
            permission_details = []
            for rp in route_permissions:
                perm_stmt = select(Permission).where(Permission.id == rp.permission_id)
                perm_result = await db.execute(perm_stmt)
                permission = perm_result.scalar_one_or_none()
                if permission:
                    permission_details.append({
                        'name': permission.name,
                        'display_name': permission.display_name,
                        'is_required': rp.is_required,
                        'is_active': rp.is_active
                    })
            
            # 检查是否包含必需的权限
            required_permissions = ['datasource.view']
            has_required = any(p['name'] in required_permissions for p in permission_details)
            
            if not has_required:
                return {
                    'success': False,
                    'message': '缺少必需的权限关联',
                    'details': {
                        'required_permissions': required_permissions,
                        'current_permissions': [p['name'] for p in permission_details]
                    }
                }
            
            self.verification_results['route_permissions'] = True
            return {
                'success': True,
                'message': '路由权限关联正确',
                'details': {
                    'route_id': datasource_route.id,
                    'permissions_count': len(permission_details),
                    'permissions': permission_details
                }
            }
            
        except Exception as e:
            logger.error(f"验证路由权限关联失败: {str(e)}")
            return {
                'success': False,
                'message': f'验证路由权限关联时发生错误: {str(e)}',
                'details': None
            }
    
    async def verify_permission_assignment(self, db: AsyncSession) -> dict:
        """验证权限分配给角色"""
        logger.info("验证数据源权限分配给角色...")
        
        try:
            # 检查数据源相关权限
            perm_stmt = select(Permission).where(Permission.resource == 'datasource')
            perm_result = await db.execute(perm_stmt)
            datasource_permissions = perm_result.scalars().all()
            
            if not datasource_permissions:
                return {
                    'success': False,
                    'message': '数据源相关权限不存在',
                    'details': '需要运行权限初始化脚本'
                }
            
            # 检查管理员角色是否有数据源权限
            admin_stmt = select(Role).where(Role.name == 'admin')
            admin_result = await db.execute(admin_stmt)
            admin_role = admin_result.scalar_one_or_none()
            
            if not admin_role:
                return {
                    'success': False,
                    'message': '管理员角色不存在',
                    'details': None
                }
            
            # 检查管理员角色的数据源权限
            admin_perms = []
            for perm in datasource_permissions:
                rp_stmt = select(RolePermission).where(
                    and_(
                        RolePermission.role_id == admin_role.id,
                        RolePermission.permission_id == perm.id
                    )
                )
                rp_result = await db.execute(rp_stmt)
                role_permission = rp_result.scalar_one_or_none()
                
                if role_permission and role_permission.is_active:
                    admin_perms.append({
                        'name': perm.name,
                        'display_name': perm.display_name
                    })
            
            if not admin_perms:
                return {
                    'success': False,
                    'message': '管理员角色未分配数据源权限',
                    'details': {
                        'admin_role_id': admin_role.id,
                        'available_permissions': [p.name for p in datasource_permissions]
                    }
                }
            
            self.verification_results['permission_assignment'] = True
            return {
                'success': True,
                'message': '权限分配正确',
                'details': {
                    'admin_role_id': admin_role.id,
                    'assigned_permissions_count': len(admin_perms),
                    'assigned_permissions': admin_perms,
                    'total_datasource_permissions': len(datasource_permissions)
                }
            }
            
        except Exception as e:
            logger.error(f"验证权限分配失败: {str(e)}")
            return {
                'success': False,
                'message': f'验证权限分配时发生错误: {str(e)}',
                'details': None
            }
    
    async def verify_user_access(self, db: AsyncSession) -> dict:
        """验证用户访问权限"""
        logger.info("验证用户访问权限...")
        
        try:
            # 检查管理员用户
            admin_stmt = select(User).where(User.username == 'admin')
            admin_result = await db.execute(admin_stmt)
            admin_user = admin_result.scalar_one_or_none()
            
            if not admin_user:
                return {
                    'success': False,
                    'message': '管理员用户不存在',
                    'details': None
                }
            
            # 检查用户是否有数据源查看权限
            # 这里简化检查，实际应该通过权限服务检查
            if admin_user.is_superuser:
                self.verification_results['user_access'] = True
                return {
                    'success': True,
                    'message': '管理员用户有超级用户权限',
                    'details': {
                        'user_id': admin_user.id,
                        'username': admin_user.username,
                        'is_superuser': admin_user.is_superuser,
                        'is_active': admin_user.is_active
                    }
                }
            
            # TODO: 这里可以添加更详细的权限检查逻辑
            
            return {
                'success': True,
                'message': '用户访问权限验证通过',
                'details': {
                    'user_id': admin_user.id,
                    'username': admin_user.username
                }
            }
            
        except Exception as e:
            logger.error(f"验证用户访问权限失败: {str(e)}")
            return {
                'success': False,
                'message': f'验证用户访问权限时发生错误: {str(e)}',
                'details': None
            }
    
    async def run_verification(self):
        """运行完整验证"""
        logger.info("开始数据源管理集成验证...")
        
        verification_results = {
            'start_time': datetime.now(),
            'route_config': None,
            'route_permissions': None,
            'permission_assignment': None,
            'user_access': None,
            'overall_success': False
        }
        
        try:
            async with get_async_session() as db:
                # 验证路由配置
                verification_results['route_config'] = await self.verify_route_configuration(db)
                
                # 验证路由权限关联
                verification_results['route_permissions'] = await self.verify_route_permissions(db)
                
                # 验证权限分配
                verification_results['permission_assignment'] = await self.verify_permission_assignment(db)
                
                # 验证用户访问权限
                verification_results['user_access'] = await self.verify_user_access(db)
                
                # 计算总体成功状态
                verification_results['overall_success'] = all([
                    verification_results['route_config']['success'],
                    verification_results['route_permissions']['success'],
                    verification_results['permission_assignment']['success'],
                    verification_results['user_access']['success']
                ])
                
                verification_results['end_time'] = datetime.now()
                verification_results['duration'] = (
                    verification_results['end_time'] - verification_results['start_time']
                ).total_seconds()
                
                return verification_results
                
        except Exception as e:
            logger.error(f"集成验证失败: {str(e)}")
            raise


def print_verification_results(results: dict):
    """打印验证结果"""
    print("\n" + "="*80)
    print("🔍 DataPlexus 数据源管理集成验证报告")
    print("="*80)
    
    # 路由配置验证
    route_config = results['route_config']
    print(f"\n📍 路由配置验证:")
    print(f"   结果: {'✅ 通过' if route_config['success'] else '❌ 失败'}")
    print(f"   消息: {route_config['message']}")
    if route_config['details']:
        if route_config['success']:
            details = route_config['details']
            print(f"   路由ID: {details['route_id']}")
            print(f"   路径: {details['path']}")
            print(f"   显示名称: {details['display_name']}")
        else:
            print(f"   详情: {route_config['details']}")
    
    # 路由权限验证
    route_perms = results['route_permissions']
    print(f"\n🔐 路由权限关联验证:")
    print(f"   结果: {'✅ 通过' if route_perms['success'] else '❌ 失败'}")
    print(f"   消息: {route_perms['message']}")
    if route_perms['details'] and route_perms['success']:
        details = route_perms['details']
        print(f"   关联权限数: {details['permissions_count']}")
        for perm in details['permissions']:
            print(f"   - {perm['name']}: {perm['display_name']}")
    
    # 权限分配验证
    perm_assign = results['permission_assignment']
    print(f"\n👥 权限分配验证:")
    print(f"   结果: {'✅ 通过' if perm_assign['success'] else '❌ 失败'}")
    print(f"   消息: {perm_assign['message']}")
    if perm_assign['details'] and perm_assign['success']:
        details = perm_assign['details']
        print(f"   管理员权限数: {details['assigned_permissions_count']}")
        print(f"   总数据源权限数: {details['total_datasource_permissions']}")
    
    # 用户访问验证
    user_access = results['user_access']
    print(f"\n👤 用户访问权限验证:")
    print(f"   结果: {'✅ 通过' if user_access['success'] else '❌ 失败'}")
    print(f"   消息: {user_access['message']}")
    
    # 总体结果
    print(f"\n🎯 总体验证结果:")
    print(f"   验证耗时: {results['duration']:.2f}秒")
    print(f"   总体状态: {'✅ 全部通过' if results['overall_success'] else '❌ 存在问题'}")
    
    if not results['overall_success']:
        print(f"\n⚠️ 修复建议:")
        if not route_config['success']:
            print("   1. 运行路由初始化脚本: python scripts/add_datasource_route.py")
        if not route_perms['success']:
            print("   2. 运行权限关联脚本: python scripts/add_datasource_route.py")
        if not perm_assign['success']:
            print("   3. 运行权限分配脚本: python scripts/init_datasource_permissions.py")
    
    print("\n" + "="*80)


async def main():
    """主函数"""
    try:
        verifier = DataSourceIntegrationVerifier()
        results = await verifier.run_verification()
        
        print_verification_results(results)
        
        return results['overall_success']
        
    except Exception as e:
        print(f"\n❌ 集成验证失败: {str(e)}")
        return False


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)
